<template>
    <div class="gd-navigation">
        <h3>导航</h3>
        <div class="info">
            <p>
                起点
                <!-- <el-input v-model="searchRoad.start" @input="changeStart"></el-input> -->
                <el-select v-model="searchRoad.start.id" filterable remote size="mini" placeholder="请输入关键词" :remote-method="startSearch" @change="startSearchChange" :loading="startPoi.loading">
                    <el-option v-for="item in startPoi.list.length > 0 ? startPoi.list : saveLocalData" :key="item.id" :label="item.address" :value="item.id" :title="item.address"> </el-option>
                </el-select>
            </p>
            <p>
                终点
                <el-select v-model="searchRoad.end.id" filterable size="mini" remote @change="endSearchChange" placeholder="请输入关键词" :remote-method="endSearch" :loading="startPoi.loading">
                    <el-option v-for="item in endPoi.list.length > 0 ? endPoi.list : saveLocalData" :key="item.id" :label="item.address" :value="item.id" :title="item.address"> </el-option>
                </el-select>
            </p>
            <el-button type="primary" size="mini" @click="searchRoadDetail">查询</el-button>
            <!-- <div class="line"></div> -->
            <el-button type="primary" size="mini" @click="showAllTip">显示所有提示</el-button>
            <!-- <div class="line"></div> -->
            <el-button type="primary" size="mini" @click="clearOverlay">移除所有提示</el-button>
        </div>
    </div>
</template>

<script>
import olMap from '../../util/lmap/lmap.js' // 引入地图包对象
import { mapState } from 'vuex'
import axios from 'axios'
export default {
    props: {
        curType: {
            type: String,
            default: ''
        }
    },
    model: {
        prop: 'curType',
        event: 'select'
    },
    data() {
        return {
            select: null,
            type: '',
            searchRoad: {
                start: {
                    id: '',
                    value: ''
                },
                end: {
                    id: '',
                    value: ''
                }
            },
            baseUrl: 'https://restapi.amap.com/v3',
            key: '5658c60a7df7f9c4c353d6024df93163',
            searchTimer: null, // 搜索定时器
            startPoi: {
                // 起点数据
                list: [],
                loading: false
            },
            endPoi: {
                // 终点数据
                list: [],
                loading: false
            },
            saveLocalData: [], // 历史查询记录
            layer: null, // 导航图层
            nameList: [],
            tipPointFeature: [], // 提示点feature
            overlayList: {} // 导航提示overlay
        }
    },
    computed: {
        ...mapState({
            map: (state) => state.map
        })
    },
    methods: {
        // 初始化绘制对象
        initSelect() {
            if (this.select) {
                // this.endDraw()
            }
            let style = {
                isIcon: false,
                stroke: {
                    color: '#aaff7f',
                    width: 2
                },
                fill: {
                    color: 'rgba(255, 255, 127, 0.6)'
                },
                icon: {
                    radius: 50,
                    stroke: {
                        color: '#0000ff',
                        width: 2
                    },
                    fill: {
                        color: 'rgba(255, 255, 127, 0.6)'
                    }
                }
            }
            olMap.draw.initSelect(olMap.map.getLayers().array_, style)
        },
        // 清除导航提示
        clearOverlay() {
            for (let key in this.overlayList) {
                olMap.map.removeOverlay(this.overlayList[key])
            }
            this.overlayList = {}
        },
        // 根据feature设置提示
        setTipPoint(feature, type = 'click') {
            console.log(feature)
            if (this.overlayList[feature.ol_uid]) {
                if (type === 'click') {
                    olMap.overlay.removeOverlay(olMap.map, this.overlayList[feature.ol_uid])
                    delete this.overlayList[feature.ol_uid]
                }
            } else {
                let gdData = feature.get('eData')
                let lonlat = feature.get('lonlat')
                console.log(gdData)
                let dom = document.querySelector('.road-overlay').cloneNode(true)
                dom.style.display = 'block'
                let content = dom.querySelector('.content')
                console.log(content)
                content.innerText = gdData.instruction
                console.log('lonlat', lonlat)
                let overlay = olMap.overlay.drawOverlay(
                    olMap.map,
                    dom,
                    lonlat,
                    { name: 'gd-point-overlay' },
                    {
                        positioning: 'bottom-left',
                        offset: [-25, -28]
                    }
                )
                console.log(feature.ol_uid)
                this.overlayList[feature.ol_uid] = overlay
            }
        },
        // 显示所有的提示
        showAllTip() {
            console.log(this.tipPointFeature)
            this.tipPointFeature.map((item) => {
                this.setTipPoint(item, '')
            })
        },
        // 起点改变
        changeStart(e) {
            console.log(e)
            if (this.searchTimer) {
                clearTimeout(this.searchTimer)
                this.searchTimer = null
            }
            if (e === '') {
                return
            }
            this.searchTimer = setTimeout(() => {
                this.getPoiByName(e)
            }, 1000)
        },
        // 起点改变
        startSearchChange(e) {
            let temp = this.startPoi.list.find((item) => {
                return item.id === e
            })
            if (!temp) {
                temp = this.saveLocalData.find((item) => {
                    return item.id === e
                })
            }
            if (temp) {
                this.searchRoad.start.value = temp.location
                this.saveSelectToLocal(temp)
            }
        },
        // 结束点改变
        endSearchChange(e) {
            let temp = this.endPoi.list.find((item) => {
                return item.id === e
            })
            if (!temp) {
                temp = this.saveLocalData.find((item) => {
                    return item.id === e
                })
            }
            if (temp) {
                this.searchRoad.end.value = temp.location
                this.saveSelectToLocal(temp)
            }
        },
        // 保存记录到本地
        saveSelectToLocal(data) {
            console.log(data)
            let temp = this.saveLocalData.find((item) => {
                return item.id === data.id
            })
            if (temp) {
                return
            }
            this.saveLocalData.push(data)
            console.log('this.saveLocalData', this.saveLocalData)
            localStorage.setItem('localCard', JSON.stringify(this.saveLocalData))
        },
        // 读取本地记录
        readLocalCard() {
            let temp = localStorage.getItem('localCard')
            if (temp) {
                this.saveLocalData = JSON.parse(temp)
            }
        },
        // 起点搜索
        async startSearch(name) {
            this.startPoi.loading = true
            this.startPoi.list = await this.getPoiByName(name)
            this.startPoi.loading = false
        },
        // 终点搜索
        async endSearch(name) {
            this.endPoi.loading = true
            this.endPoi.list = await this.getPoiByName(name)
            this.endPoi.loading = false
        },
        // 根据中文名查询poi
        async getPoiByName(name) {
            let url = this.baseUrl + '/place/text'
            let params = {
                key: this.key,
                keywords: name,
                page_size: 50
            }
            const res = await axios.get(url, {
                params: params
            })
            if (res.data.info === 'OK') {
                return res.data.pois
            } else {
                return []
            }
        },
        // 清除单行信息
        clearRoadDetail() {
            olMap.layer.clear(this.layer)
            this.clearOverlay()
            this.tipPointFeature = []
        },
        // 查询导航信息
        searchRoadDetail() {
            this.clearRoadDetail()
            let url = this.baseUrl + '/direction/walking'
            let params = {
                key: this.key,
                keywords: name,
                origin: this.searchRoad.start.value,
                destination: this.searchRoad.end.value
            }
            axios
                .get(url, {
                    params: params
                })
                .then((res) => {
                    console.log(res)
                    if (res.data.info.toUpperCase() === 'OK') {
                        if (!this.layer) {
                            this.layer = olMap.layer.GeoJsonVector(olMap.map)
                            this.layer.setZIndex(10001)
                        }
                        let data = res.data.route.paths[0]
                        olMap.utils.panTo(olMap.map, this.handlerData(data.steps[0].polyline)[0], 12)

                        data.steps.map((item) => {
                            olMap.polygon.drawPolygon(this.layer, null, this.handlerData(item.polyline), 'line', { name: 'gd-line' })
                            let pointFeature = this.drawTipPoint(item)
                            this.tipPointFeature.push(pointFeature)
                        })
                    }
                })
        },
        // 绘制提示点
        drawTipPoint(data) {
            let style = {
                isIcon: true,
                icon: {
                    src: require('../../assets/images/position.png'),
                    size: [40, 50],
                    scale: 0.8,
                    offset: [0, 0]
                }
            }
            let lonlat = this.handlerData(data.polyline)[0]
            return olMap.polygon.drawPolygon(this.layer, style, lonlat, 'point', {
                name: 'gd-point',
                eData: data,
                lonlat: lonlat
            })
        },
        handlerData(data) {
            let arr = data.split(';')
            let res = []
            arr.map((item) => {
                let t = item.split(',')
                for (let key in t) {
                    t[key] = parseFloat(t[key])
                }
                res.push(t)
            })
            return res
        }
    },
    created() {
        this.readLocalCard()
    },
    mounted() {}
}
</script>

<style scoped lang="less">
.gd-navigation {
    h3 {
        margin: 5px 0;
        font-size: 20px;
        text-align: center;
    }

    .info {
        p {
            margin-bottom: 10px;
        }
    }
}
</style>
